//
//  DJHttpTool.m
//  ETC_ios
//
//  Created by xinrui on 2017/12/4.
//  Copyright © 2017年 xinrui. All rights reserved.
//

#import "DJHttpTool.h"
#import "AFNetworking.h"

@implementation DJHttpTool
+ (void)updateImageWithURL:(NSString *)url params:(NSDictionary *)params datas:(NSArray *)datas name:(NSString *)name success:(void (^)(id))success failure:(void (^)(NSError *))failure {
    
    //url=[BaseUrl stringByAppendingString:url];
    AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];
    NSMutableURLRequest *request = [serializer multipartFormRequestWithMethod:@"POST" URLString:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        for (int i = 0; i < datas.count; i++) {
            NSData *data = datas[i];
            if ([@"attachment" isEqualToString:name]) {
                NSString *newName = name;
                if (i == 0) {
                    newName = [NSString stringWithFormat:@"%@", name];
                } else {
                    newName = [NSString stringWithFormat:@"%@%d", name, i + 1];
                }
                [formData appendPartWithFileData:data name:newName fileName:[NSString stringWithFormat:@"%@.jpg",name] mimeType:@"image/jpeg"];
            } else {
                NSString *newName = name;
                NSRange range = [name rangeOfString:@"photo"];
                if (range.length == 0) {
                    newName = [NSString stringWithFormat:@"%@%d", name, i + 1];
                }
                [formData appendPartWithFileData:data name:newName fileName:[NSString stringWithFormat:@"%@.jpg",name] mimeType:@"image/jpeg"];
            }
        }
    } error:nil];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSProgress *progress = nil;

    
    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) {
        dispatch_async(dispatch_get_main_queue(), ^{
            // progress
        });
    } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (!error) {
            if (success) {
                success(responseObject);
            }
        } else {
            if (failure) {
                failure(error);
            }
        }
    }];
    
    [uploadTask resume];
}


//发送一个post请求

+ (void)postWithURL:(NSString *)url params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure
{
    // url=[BaseUrl stringByAppendingString:url];
    // 1.创建请求管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setValue:@"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36" forHTTPHeaderField:@"User-Agent"];
    // 2.设置超时时间
   [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 10.f;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    //3.设置请求参数的类型
   [manager.requestSerializer setStringEncoding:NSUTF8StringEncoding];

    manager.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@"text/html",@"application/json",@"text/json",nil];
    MYLog(@"Post 请求的参数=%@  \n  请求的地址=%@",params,url);
    
    [manager POST:url parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject) {
        // responseObject = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSString *responseStr=[DJTool convertToJsonData:responseObject];

        MYLog(@"Post  返回的数据=%@",responseStr);
        
        if (success) {
                success(responseObject);
            }
    } failure:^(NSURLSessionTask *operation, NSError *error) {
//        [DJToast showCenterToast:@"网络请求错误,请检查网络"];
        MYLog(@"Post  失败的原因=%@",error);
        if (failure) {
            failure(error);
        }
    }];
    
}

+ (void)postWithURL:(NSString *)url params:(NSDictionary *)params formData:(FCFormData *)formData success:(void (^)(id))success failure:(void (^)(NSError *))failure
{
    // url=[BaseUrl stringByAppendingString:url];
   
    // 1.创建请求管理对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setStringEncoding:NSUTF8StringEncoding];

    // 2.发送请求
    [manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull totalFormData) {
        [totalFormData appendPartWithFileData:formData.data name:formData.name fileName:formData.filename mimeType:formData.mimeType];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (success) {
            success(error);
        }
    }];
}

+ (void)getWithURL:(NSString *)url params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure {
   
   //  url=[BaseUrl stringByAppendingString:url];
    // 1.创建请求管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setStringEncoding:NSUTF8StringEncoding];
    [manager.requestSerializer setValue:@"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36" forHTTPHeaderField:@"User-Agent"];

    // 2.设置超时时间
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 10.f;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    //3.设置请求参数的类型
    manager.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@"text/html",@"application/json",@"text/json",nil];
    MYLog(@"Get  请求的参数=%@  \n  请求的地址=%@",params,url);
    //4.发送请求
    [manager GET:url parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject) {
        NSString *responseStr = [DJTool convertToJsonData:responseObject];
        MYLog(@"Get  返回的数据=%@",responseStr);
        
        if (success) {
            success(responseObject);
        }
    } failure:^(NSURLSessionTask *operation, NSError *error) {
        MYLog(@"Get 失败的原因=%@",error);

        if (failure) {
            failure(error);
        }
    }];
}

+ (void)updateImageWithUrl:(NSString *)url params:(NSDictionary *)params path:(NSString *)path success:(void (^)(id))success failure:(void (^)(NSError *))failure  {
    //  url = [BASE_URL stringByAppendingString:url];
    
    AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];
    
    NSMutableURLRequest *request = [serializer multipartFormRequestWithMethod:@"POST" URLString:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileURL:[NSURL fileURLWithPath:path] name:@"uploadImage" fileName:[path lastPathComponent] mimeType:@"application/octet-stream" error:nil];
    } error:nil];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    NSProgress *progress = nil;
    
    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) {
        dispatch_async(dispatch_get_main_queue(), ^{
            // progress
        });
    } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (!error) {
            if (success) {
                success(responseObject);
            }
        } else {
            if (failure) {
                failure(error);
            }
        }
    }];
    
    [uploadTask resume];
}


+(void)downloadURL:(NSDictionary *)dic progress:(void (^)(NSProgress *downloadProgress))progress destination:(void (^)(NSURL *targetPath))destination failure:(void(^)(NSError *error))faliure{
    
    //1.创建管理者
    AFHTTPSessionManager *manage  = [AFHTTPSessionManager manager];
    manage.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"audio/mpeg"];
    //2.下载文件
    /*
     第一个参数：请求对象
     第二个参数：下载进度
     第三个参数：block回调，需要返回一个url地址，用来告诉AFN下载文件的目标地址
     targetPath：AFN内部下载文件存储的地址，tmp文件夹下
     response：请求的响应头
     返回值：文件应该剪切到什么地方
     第四个参数：block回调，当文件下载完成之后调用
     response：响应头
     filePath：文件存储在沙盒的地址 == 第三个参数中block的返回值
     error：错误信息
     */
    
    //2.1 创建请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString: dic[@"url"]]];
    
    NSURLSessionDownloadTask *downloadTask = [manage downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {//进度
         NSLog(@"%f",1.0 *downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
        if (downloadProgress) {
            progress(downloadProgress);
        }
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
//        NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        NSString * duc = [JHFileManger getDocumentsPath];
        //拼接文件全路径
        NSString *fullpath = @"";
        if (dic[@"name"])
        {
            fullpath = [duc stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@", dic[@"fileName"], dic[@"name"]]];
        }
        else
        {
            fullpath = [duc stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@.zip", dic[@"fileName"], dic[@"fileName"]]];
        }
        NSURL *filePathUrl = [NSURL fileURLWithPath:fullpath];
        
        return filePathUrl;
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nonnull filePath, NSError * _Nonnull error) {
        
        
        if (error) {
            faliure(error);
        }
        
        
        if(filePath){
            
            destination(filePath);
        }
    }];
    
    //3.启动任务
    [downloadTask resume];
}



//获取当前时区的当前时间
+ (NSString*)nowTime:(NSString*)dateType
{
    NSDate * date = [NSDate date];
    NSDateFormatter *dateformat=[[NSDateFormatter alloc] init];
    //[dateformat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    [dateformat setDateFormat:dateType];
    NSString * newDate= [dateformat stringFromDate:date];
    return newDate;
}


@end

/**
 *  用来封装文件数据的模型
 */
@implementation FCFormData

@end


